package me.evis.mobile.sms2cal.parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.os.Process;
import android.util.Log;

public class Util {
    /** Tag string for debug logs */
    private static final String TAG = "me.evis.mobile.sms2cal.parser.Util";
    
    private static final String UID_HOST = "sms2cal.evis.me";
    
    private static final String UTC_ID = "Etc/UTC";
    private static final String DEFAULT_PATTERN = "yyyyMMdd'T'HHmmss";
    private static final String UTC_PATTERN = "yyyyMMdd'T'HHmmss'Z'";
    //private static final String RELAXED_PATTERN = "yyyyMMdd";
    private static final DateFormat DEFAULT_FORMAT;
    static {
        DEFAULT_FORMAT = new SimpleDateFormat(DEFAULT_PATTERN);
        DEFAULT_FORMAT.setLenient(false);
    }
    private static final DateFormat UTC_FORMAT;
    static {
        UTC_FORMAT = new SimpleDateFormat(UTC_PATTERN);
        UTC_FORMAT.setTimeZone(TimeZone.getTimeZone(UTC_ID));
        UTC_FORMAT.setLenient(false);
    }
    
    public static final String NL = "\n";
    
    private Util() {
        // no instance.
    }
    
    public static String getCalEventUid(Date stamp) {
        return new StringBuffer()
                .append(UTC_FORMAT.format(stamp)).append("-")
                .append(Process.myPid()).append(UID_HOST)
                .toString();
    }
    
    public static String getDateTimeDefaultFormat(Date date) {
        if (date != null) {
            return DEFAULT_FORMAT.format(date);
        } else {
            return "N/A";
        }
    }

    public static Pattern compileRegex(String regexStr) {
        Pattern regex = null;
        try {
            regex = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE);
        } catch (PatternSyntaxException e) {
            // TODO consider throw it out.
            Log.e(TAG, "Pattern string \"" + regexStr + "\" is invalid.", e);
        }
        return regex;
    }
    
    public static String readAsString(InputStream is) throws IOException {
        final char[] buffer = new char[0x10000];
        StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, "UTF-8");
        int read;
        do {
          read = in.read(buffer, 0, buffer.length);
          if (read>0) {
            out.append(buffer, 0, read);
          }
        } while (read>=0);
        
        return out.toString();
    }
}
